//
//  MenuitemViewController.m
//  clublbiza
//
//  Created by WANG TOM on 9/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MenuitemViewController.h"
#import "clublbizaAppDelegate.h"
#import "TMDataTable.h"

@interface MenuitemViewController ()

@end

@implementation MenuitemViewController
@synthesize recordView;
@synthesize nameEnView;
@synthesize menuUUID;
@synthesize seperatorView;
@synthesize nameCnView;
@synthesize previousButton;
@synthesize nextButton;
@synthesize pageInfoView;
@synthesize mainBackgroundImage;

@synthesize previousVersionId,nextVersionId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    //Init catalog title
    self.previousVersionId = -1;
    self.nextVersionId = -1;
    
    [self refreshBackGrounImage];
    [self reloadAllViewData];
}
-(void) reloadAllViewData 
{
    AppMain *appMain = [AppMain shareInstance];
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    TMDataTable *dt = nil;
    if ( appMain.currentSelectedMenuTabIndex == 0 ) {
        dt = [[TMDataTable alloc] initWithTablename:@"Beverage" withPKName:@"uuid" contextProvider:appDelegate]; 
    } else {
        dt = [[TMDataTable alloc] initWithTablename:@"Food" withPKName:@"uuid" contextProvider:appDelegate];
    }
    NSManagedObject *menuData = [dt findByField:@"version_id" withValue:[NSNumber numberWithInt:appMain.currentSelectedMenuVersionId] withSort:nil];
    
    self.nameEnView.text = [menuData valueForKey:@"name_en"];
    self.nameCnView.text = [menuData valueForKey:@"name_cn"];
    
    self.menuUUID = [menuData valueForKey:@"uuid"];;
    
    
    
    //set color
    
    [self.seperatorView setBackgroundColor:[UIColor colorWithRed:0 green:255 blue:255 alpha:1.0]];
    [self.nameEnView setTextColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
    [self.nameCnView setTextColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
    [self.pageInfoView setTextColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
    
    [dt release];
    [self refreshDataListView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    [self releaseRetainResourc];
    
}
- (void) releaseRetainResourc
{
    self.recordView = nil;
    self.nameEnView = nil;
    self.seperatorView = nil;
    self.nameCnView = nil;
    self.previousButton = nil;
    self.nextButton = nil;
    self.pageInfoView = nil;
    self.mainBackgroundImage = nil;
    
    [self.menuUUID release];
    
    NSLog(@"video list unload");
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

-(IBAction)backMenuList:(id)sender
{
    [self.menuUUID release];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void) refreshDataListView
{
    //Remove all item views
    NSArray *subviews = [[self.recordView subviews] copy];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    [subviews release];
    
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    TMDataTable *dt = nil;
    AppMain *appMain = [AppMain shareInstance];
    if ( appMain.currentSelectedMenuTabIndex == 0 ) {
        dt = [[TMDataTable alloc] initWithTablename:@"Beverage_item" withPKName:@"uuid" contextProvider:appDelegate]; 
    } else {
        dt = [[TMDataTable alloc] initWithTablename:@"Food_item" withPKName:@"uuid" contextProvider:appDelegate];
    }
       
    NSString *condition = [NSString stringWithFormat:@"parent_uuid='%@' AND active=1", self.menuUUID ];
    NSArray *data_list = [dt findAll:condition withSort:@"order"];
    
    int i = 0;
    int total_height = 0;
    for(NSManagedObject *data_row in data_list)
    {
        

        UIView *itemView = [self itemViewBuilder:[data_row valueForKey:@"name_en"] withCNTitle:[data_row valueForKey:@"name_cn"] withPriceInfo:[data_row valueForKey:@"price"]];
        
        CGRect frame = itemView.frame;
        frame.origin.y = i*(frame.size.height + 15);
        itemView.frame = frame;
        
        [self.recordView addSubview:itemView];
        
        total_height = frame.origin.y + frame.size.height;
        i++;
        
    }
    CGSize scrollViewSize = self.recordView.contentSize;
    scrollViewSize.height = total_height;
    [self.recordView setContentSize:scrollViewSize];
    
    
    //toggle previous and next button
    /*
    self.nextButton.hidden = YES;
    self.previousButton.hidden = YES;
    if ( self.pageIndex > 0) {
        self.previousButton.hidden = NO;
    }
    int totalPage = ceil((float)videoListAll.count/ITEM_PAGE_SIZE);
    
    if ( self.pageIndex < (totalPage - 1)) {
        self.nextButton.hidden = NO;
    }
    //page info
    if ( totalPage > 0 ) {
        self.pageInfoView.text = [NSString stringWithFormat:@"total %d page %d of %d",videoListAll.count,self.pageIndex+1,totalPage];
    } else {
        self.pageInfoView.text = @"";
    }
    */
    [dt release];
    
    [self refreshPaginationButtonStatus];
}
- (void) refreshPaginationButtonStatus
{
    AppMain *appMain = [AppMain shareInstance];
    int tmp_previousVersionId = - 1;
    int  tmp_currentVersionId = -1;
    self.previousVersionId = -1;
    self.nextVersionId = -1;
    
    int current_index = 1;
    int current_selected_menu_index = 1;
    for(NSManagedObject *menuData in appMain.cacheMenuItemListData) 
    {
         tmp_currentVersionId = [[menuData valueForKey:@"version_id"] intValue];
        if (  tmp_currentVersionId == appMain.currentSelectedMenuVersionId ) 
        {
            self.previousVersionId =  tmp_previousVersionId;
            
            current_selected_menu_index = current_index;
        }
        
        if (  tmp_previousVersionId == appMain.currentSelectedMenuVersionId ) {
            self.nextVersionId =  tmp_currentVersionId;
        }
        tmp_previousVersionId =  tmp_currentVersionId;
        
        current_index++;
    }
    self.nextButton.hidden = YES;
    self.previousButton.hidden = YES;
    
    if ( self.nextVersionId > 0 ) {
         self.nextButton.hidden = NO;
    }
    if ( self.previousVersionId > 0 ) {
        self.previousButton.hidden = NO;
    }
    
    //page info
    self.pageInfoView.text = [NSString stringWithFormat:@"菜单 %d/%d",current_selected_menu_index,appMain.cacheMenuItemListData.count];
}

- (UIView*) itemViewBuilder:(NSString*)title withCNTitle:(NSString*)title_cn  withPriceInfo:(NSString*)priceInfo
{
    UIView *itemView = [[UIView alloc] init];
    [itemView setFrame:CGRectMake(0, 0, 950, 100)];
    
    //Add arrow view
    UIImage *arrowImage = [UIImage imageNamed:@"arrow_right.png"];
    UIImageView *arrowView = [[UIImageView alloc] initWithImage:arrowImage];
    arrowView.frame = itemView.frame;
    arrowView.contentMode = UIViewContentModeScaleToFill;
    [arrowView setFrame:CGRectMake(2, 5, 10, 11)];
    [itemView addSubview:arrowView];
    [arrowView release];
    
    //title view
    UILabel *titleObj = [[UILabel alloc] init];
    titleObj.textAlignment = UITextAlignmentLeft; 
    titleObj.lineBreakMode = UILineBreakModeWordWrap;  
    titleObj.numberOfLines = 0; 
    titleObj.backgroundColor = [UIColor clearColor];
    titleObj.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    
    
    CGSize sz = [title sizeWithFont:titleObj.font constrainedToSize:CGSizeMake(600, 1000)];
    [titleObj setFrame:CGRectMake(20, 0, 600, sz.height)];
    titleObj.text = title;
    
    [itemView addSubview:titleObj];
    [titleObj release];
    
    //price info
    UILabel *priceObj = [[UILabel alloc] init];
    priceObj.backgroundColor = [UIColor clearColor];
    priceObj.lineBreakMode = UILineBreakModeWordWrap;  
    priceObj.numberOfLines = 0; 
    priceObj.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    priceObj.textAlignment = UITextAlignmentRight;
 
    if ( priceInfo  != nil ) {
        sz = [priceInfo sizeWithFont:priceObj.font constrainedToSize:CGSizeMake(200, 1000)];
        [priceObj setFrame:CGRectMake(750, 0, 200, sz.height)];
        priceObj.text = priceInfo;
    }else{
        priceObj.text = @"无";
    }
    [itemView addSubview:priceObj];
    [priceObj release];
    //sub title
    UILabel *titleCNObj = [[UILabel alloc] initWithFrame:CGRectMake(20, titleObj.frame.origin.y + titleObj.frame.size.height + 10, 600, 30)];
    titleCNObj.text = title_cn;
    titleCNObj.backgroundColor = [UIColor clearColor];
    titleCNObj.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    [itemView addSubview:titleCNObj];
    [titleCNObj release];
    
    //seperate view
    UIView *seperaterView = [[UIView alloc] initWithFrame:CGRectMake(0, titleCNObj.frame.origin.y + titleCNObj.frame.size.height + 10, itemView.frame.size.width, 1)];
    [seperaterView setBackgroundColor:[UIColor colorWithRed:0 green:255 blue:255 alpha:0.3]];
    [itemView addSubview:seperaterView];
    [seperaterView release];

    
    return [itemView autorelease];
}

- (IBAction)previousPage:(id)sender
{
    AppMain *appMain = [AppMain shareInstance];
    appMain.currentSelectedMenuVersionId = self.previousVersionId;
     [self reloadAllViewData];
}
- (IBAction)nextPage:(id)sender
{ 
    AppMain *appMain = [AppMain shareInstance];
    appMain.currentSelectedMenuVersionId = self.nextVersionId;
    [self reloadAllViewData];
    
}

- (void) refreshBackGrounImage
{
    NSString *defaultKeyName = APPLICATION_BACKGROUND_IMAGE_NAME_3;
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isCustomize = [userDefaults stringForKey:defaultKeyName];
    if (isCustomize != nil){
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        
        NSString *bgImgPath = [documentsPath stringByAppendingFormat:@"/%@",defaultKeyName];
        UIImage *image = [UIImage imageWithContentsOfFile:bgImgPath];
        self.mainBackgroundImage.image = image;
    }else {
        UIImage *image = [UIImage imageNamed:@"bg3.jpg"];
        self.mainBackgroundImage.image = image;
    }
}
@end
